<?php
/**
 * Created by PhpStorm.
 * User: shutao
 * Date: 2019-01-11
 * Time: 13:56
 */

namespace wechat\services;

use wechat\models\WeUser;
use wechat\models\WeUserOpenid;

class WeUserService
{
    /**
     * 获取用户指定微信号下的 openid
     * @param integer $uid 当前用户的 id
     * @param string $appid 公众号/小程序的 appid
     * @return string 用户的 openid
     */
    public static function openid($uid, $appid)
    {
        static $command;
        if (is_null($command)) {
            $sql = 'SELECT uo.user_openid FROM `' . WeUser::tableName() .
                '` as u LEFT JOIN `' . WeUserOpenid::tableName() .
                '` as uo ON u.id = uo.we_id WHERE u.uid = :uid AND uo.openid = :openid';
            $command = \Yii::$app->db->createCommand($sql);
        }
        $data = $command->bindValues([':uid' => $uid, ':openid' => $appid])->queryOne();
        return isset($data['user_openid']) ? $data['user_openid'] : '';
    }
}